//
//  JPRefreshControl.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 16/9/27.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit

let JPRefreshHeight: CGFloat = 35

enum JPRefreshStatus {
    
    //  下拉刷新
    case normal
    //  松手即刷新
    case pulling
    //  正在刷新
    case refresh
}

class JPRefreshControl: UIControl {
    
    //  状态图
    private lazy var statusImage: UIImageView = {
        let statusImage = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
        statusImage.sizeToFit()
        return statusImage
    }()
    
    //  状态提示
    private lazy var statusLabel: UILabel = {
        let statusLabel = UILabel()
        statusLabel.text = "下拉刷新"
        statusLabel.font = UIFont.systemFont(ofSize: 12)
        statusLabel.textColor = UIColor.darkGray
        return statusLabel
    }()
    
    //  刷新图片
    private lazy var refreshView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    
    //  父视图
    var superView: UIScrollView?
    
    //  控件状态
    var refreshStatus: JPRefreshStatus = .normal {
        didSet {
            switch refreshStatus {
            case .normal:
                statusLabel.text = "下拉刷新"
                UIView.animate(withDuration: 0.25, animations: {
                    self.statusImage.transform = CGAffineTransform.identity
                    })
                
                if oldValue == .refresh {
                    statusImage.isHidden = false
                    UIView.animate(withDuration: 0.25, animations: {
                        self.superView?.contentInset.top -= JPRefreshHeight
                        }, completion: { (true) in
                            self.refreshView.stopAnimating()
                    })
                }
                
            case .pulling:
                statusLabel.text = "松手即刷新"
                UIView.animate(withDuration: 0.25, animations: { 
                    self.statusImage.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                    })
                
            case .refresh:
                UIView.animate(withDuration: 0.25, animations: {
                    self.superView?.contentInset.top += JPRefreshHeight
                })
                statusLabel.text = "正在加载"
                statusImage.isHidden = true
                refreshView.startAnimating()
                
    
                sendActions(for: .valueChanged)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  获取父视图
    override func willMove(toSuperview newSuperview: UIView?) {
        
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        self.frame = CGRect(x: 0, y: -JPRefreshHeight, width: screenWidth, height: JPRefreshHeight)
        
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        superView = scrollView
    }
    
    //  观察者方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        guard let contentOffsetY = superView?.contentOffset.y else {
            return
        }
        
        let maxY = -JPRefreshHeight - (superView?.contentInset.top)!
//        print(contentOffsetY)
        
        if superView!.isDragging {
            
            if contentOffsetY < maxY && refreshStatus == .normal {
                print("下拉刷新")
                refreshStatus = .pulling
            }else if contentOffsetY >= maxY && refreshStatus != .normal{
                print("putong")
                refreshStatus = .normal
            }
            
        }else {
            if refreshStatus == .pulling{
                
                refreshStatus = .refresh
                print("松手")
            }
        }
    }
    
    //  停止刷新
    func endRefreshing() {
        refreshStatus = .normal
    }
    
    func setupUI() {
        
        self.backgroundColor = UIColor.red
        
        addSubview(statusImage)
        addSubview(statusLabel)
        addSubview(refreshView)
        
        statusImage.translatesAutoresizingMaskIntoConstraints = false
        statusLabel.translatesAutoresizingMaskIntoConstraints = false
        refreshView.translatesAutoresizingMaskIntoConstraints = false
        
        
        addConstraint(NSLayoutConstraint(item: statusImage, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: statusImage, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: statusLabel, attribute: .centerY, relatedBy: .equal, toItem: statusImage, attribute: .centerY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: statusLabel, attribute: .left, relatedBy: .equal, toItem: statusImage, attribute: .right, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .centerX, relatedBy: .equal, toItem: statusImage, attribute: .centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .centerY, relatedBy: .equal, toItem: statusImage, attribute: .centerY, multiplier: 1, constant: 0))
        
    }
}
